<?php
declare (strict_types = 1);

namespace app\admin\controller;

use app\common\Controller;

abstract class BaseController extends Controller
{
    //排除登录校验的action
    protected $excludeCheckLogin = [];

    //会话Key
    private $session_key;

    //用户信息
    private $user = [];

    protected function initialize()
    {
        $action = $this->request->action();
        if (is_string($this->excludeCheckLogin)) {
            $this->excludeCheckLogin = [$this->excludeCheckLogin];
        }
        if (is_array($this->excludeCheckLogin) && in_array($action, $this->excludeCheckLogin)) {
            return;
        }
        $this->checkLogin();
    }

    protected function checkLogin()
    {
        $token = $this->request->header('authorization');
        if (empty($token) && $this->app->isDebug()) {
            $token = cookie('admin_token');
        }
        if (empty($token)) {
            failure(3);
        }

        $redis = redis_handle();
        $prefix = config('redis.default.prefix');
        $this->session_key = "{$prefix}:admin_login:{$token}";
        $session_value = $redis->get($this->session_key);
        if (empty($session_value)) {
            $redis->close();
            failure(3);
        }
        $userInfo = json_decode($session_value, true);
        if (empty($userInfo)) {
            $redis->close();
            failure(3);
        }
        $redis->expire($this->session_key, $userInfo['expire']);
        $redis->close();
        $this->user = $userInfo;
    }

    protected function getSessionKey()
    {
        return $this->session_key;
    }

    protected function getUserInfo()
    {
        return $this->user;
    }

    protected function getUserId()
    {
        return $this->user['id'];
    }
}
